<?php

namespace models;

//如
// 1. http://t.dianping.com/deal/21302898
use util\CommonUtil;

class DianPingTcomSpider extends BaseSpider {

    // 初始化webUrl、apiUrl
    function __construct($url, $ua){
        $this->ua = $ua;
        $this->webUrl = $url;
        $url = explode('?',$url)[0];
        $id = 0;
        if(preg_match('/([0-9]+)/',$url,$matches)){
            $id = $matches[1];
        }
        if ($id != 0) {
            $this->apiUrl = "http://t.dianping.com/ajax/detailDealRate?dealGroupId={$id}&pageNo=1&filtEmpty=1&timestamp=1508919140855";
        }

    }

    // 获取评论列表，仅处理10条
    public function getComments(){

        if (empty($this->apiUrl)) return [];

        $ch = curl_init();
        $timeout = 30;
        curl_setopt ($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);

        $html = str_get_html($file_contents);
        $liList = $html->find('li[class=Fix]');
        $num = 0;
        $arr = array();
        foreach($liList as $li){
            if($num < 10){
                $num ++;
                $obj = array();
                $obj['nickname'] = $li->find('span[class=name]')[0]->innertext;//昵称
                $obj['content'] = $li->find('div[class=J_brief_cont_full]')[0]->innertext;//评论内容
                $obj['comment_time'] = CommonUtil::checkTime($li->find('span[class=date]')[0]->innertext);//评论时间
                $arr[] = $obj;
            }
        }
        return $arr;
    }
	
}